<?php

namespace app\model\iot_model;

use app\BaseModel;
use app\common\Message;
use app\model\sync_model\SyncOperlog;
use app\model\sync_model\SyncUser;
use app\model\UnitModel;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;

class IotDevice extends BaseModel
{
    use Message;
    protected $name = 'iot_device';

    /**
     * 关联设备分类-获取设备名称
     * @return BelongsTo
     */
    public function deviceForName(): BelongsTo
    {
        return $this->belongsTo(IotDeviceCategory::class, 'name')->bind(['dev_name'=>'name']);
    }

    /**
     * 关联同步过来的用户表
     * @return HasMany
     */
    public function userNum(): HasMany
    {
        return $this->hasMany(SyncUser::class, 'device_id')->field('device_id');
    }

    /**
     * 关联同步过的模块表
     * @return HasMany
     */
    public function getModuleNum(): HasMany
    {
        return $this->hasMany(SyncOperlog::class,'device_id')->where('type',1)->field('device_id,title,type,add_time');
    }

    /**
     * 关联同步过的模块表-计算登录次数
     * @return HasMany
     */
    public function useCount(): HasMany
    {
        return $this->hasMany(SyncOperlog::class,'device_id')->where('type',5)->field('device_id,title,type,add_time');
    }

    /**
     * 关联单位-单位名称
     * @return BelongsTo
     */
    public function unitName(): BelongsTo
    {
        return $this->belongsTo(UnitModel::class,'company_id')->bind(['unit_name'=>'name']);
    }
}